﻿using JamesZhao.Engine.Graphics.Effects;
using JamesZhao.Engine.Graphics.Surfaces;
using JamesZhao.Engine.Graphics.Visuals;
using SlimDX;
using SlimDX.Direct3D11;
using SlimDX.DXGI;

namespace JamesZhao.Engine.Graphics.RenderStages
{
    internal class GenerateGBufferStage : RenderStage
    {
        public GenerateGBufferStage(GraphicsDevice device)
        {
            GenGBufferEffect = new GpuProgram(device, "Shaders/GenGBuffer.fx");
        }

        public DepthSurface DepthSurface { get; set; }

        public GpuProgram GenGBufferEffect { get; set; }

        public GBuffer GBuffer { get; set; }

        public override string Name
        {
            get { return "Generate GBuffer"; }
        }

        protected override void OnRender(GraphicsDevice device, SwapChain swapChain, VisualsList visualsList,
                                         Camera camera)
        {
            device.ImmediateContext.ClearRenderTargetView(GBuffer.Normal.TargetView, new Color4(0, 0, 0, 0));
            device.ImmediateContext.ClearRenderTargetView(GBuffer.Depth.TargetView, new Color4(0, 0, 0, 0));
            device.ImmediateContext.ClearDepthStencilView(DepthSurface.DepthView, DepthStencilClearFlags.Depth, 1, 0);

            device.ImmediateContext.OutputMerger.SetTargets(DepthSurface.DepthView,
                                                            new[]
                                                                {
                                                                    GBuffer.Depth.TargetView,
                                                                    GBuffer.Albedo.TargetView,
                                                                    GBuffer.Normal.TargetView,
                                                                });
            GenGBufferEffect.ScalarVariables["zFar"].Set(camera.Lens.Far);
            foreach (Drawable renderable in visualsList.Drawables)
            {
                renderable.RenderWithGpuProgram(device, camera, GenGBufferEffect);
            }
        }
    }
}